﻿using ConfExpert.Forms.Base;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPivotGrid;
using DevTeam;

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Teknik
{
    public partial class _Metraj : XForm
    {
        /*
select 'update bm14 set ' + COLUMN_NAME+ ' = replace('+COLUMN_NAME+','','',''.'')'
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'BM14'
        */

        RepositoryItemComboBox riLine
        {
            get
            {
                RepositoryItemComboBox ri = new RepositoryItemComboBox();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;
                ri.Items.AddRange(new object[] { "ERKEK", "BAYAN", "ÇOCUK", "ÇOCUK KIZ", "ÇOCUK ERKEK" });
                return ri;
            }
        }

        RepositoryItemComboBox riNumuneUretim
        {
            get
            {
                RepositoryItemComboBox ri = new RepositoryItemComboBox();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;
                ri.Items.AddRange(new object[] { "NUMUNE", "ÜRETİM", "KOLEKSİYON" });
                return ri;
            }
        }

        RepositoryItemComboBox riYikamaBilgisi
        {
            get
            {
                RepositoryItemComboBox ri = new RepositoryItemComboBox();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;
                ri.Items.AddRange(new object[] { "YIKAMALI", "YIKAMASIZ" });
                return ri;
            }
        }


        public _Metraj()
        {
            InitializeComponent();

            TAM.BMTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.BMTableAdapter();
            TAM.BMLinesTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.BMLinesTableAdapter();
        }

        BindingSource bsBM, bsLines;
        private void Metraj_Load(object sender, EventArgs e)
        {
            btnKaydet.Enabled = ytk(61);   //sadece Emel Sandıkçı + Mine Akyol kaydedebilsin diye

            TAM.BrandTableAdapter = new Datasets.MyDataTableAdapters.BrandTableAdapter();
            TAM.BrandTableAdapter.Fill(ds.Brand);

            //ds.BM.Columns.Add("CustomerId", typeof(decimal), "Parent(FK_BM_Brand_BrandId).CustomerId");
            ds.BM.Columns.Add("BirimMetraj", typeof(decimal), "AVG(Child(FK_BMLines_BM_idx).BirimMetraj)");
            //ds.BM.Columns.Add("BirimMetraj", typeof(decimal), "AVG(Child(FK_BMLines_BM_idx).BirimMetraj)");

            bsBM = new BindingSource(ds, "BM");
            bsLines = new BindingSource(bsBM, "FK_BMLines_BM_idx");
            AddBsToList(bsBM, bsLines);

            //GridManager.Initialize(Enums.FormId.Metraj,
            //    new GridView[] { gvMetraj },
            //    new BindingSource[] { bsBM });

            InitGridView(gvMetraj, bsBM);

            //gvMetraj.ShowFindPanel();
            gvMetraj.Columns["Line"].ColumnEdit = riLine;
            gvMetraj.Columns["NumuneUretim"].ColumnEdit = riNumuneUretim;
            gvMetraj.Columns["YikamaBilgisi"].ColumnEdit = riYikamaBilgisi;
            gvMetraj.Columns["UserId"].Visible = false;
            gvMetraj.AddSummary("Adet");
            AddAverage(gvMetraj, /*"BirimMetrajP1", "NumuneBirimMetrajP1",*/ "Garni1CM", "Garni2CM", "Garni3CM", "Garni4CM", "Garni5CM");

            gvMetraj.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
            gvMetraj.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(gvMetraj_FocusedRowChanged);

            InitGridView(gvLines, bsLines);
            gvLines.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;

            foreach (string str in "CekmeEN;CekmeBOY".Split(';'))
            {
                gvLines.Columns[str].Caption = gvLines.Columns[str].FieldName + "%";

                gvLines.Columns[str].ColumnEdit = new RepositoryItemTextEdit();
                ((RepositoryItemTextEdit)gvLines.Columns[str].ColumnEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                ((RepositoryItemTextEdit)gvLines.Columns[str].ColumnEdit).DisplayFormat.Format = new FormatYuzde(); //"{0:p0}";
            }

            gvLines.Columns["idx"].Visible = gvLines.Columns["BMLinesId"].Visible = false;

            gvMetraj.RowCellStyle += new RowCellStyleEventHandler(gvMetraj_RowCellStyle);
            gvLines.RowCellStyle += new RowCellStyleEventHandler(gvMetraj_RowCellStyle);
            gvMetraj.OptionsView.ShowBands = true;
            bsBM.CurrentChanged += new EventHandler(bsBM_CurrentChanged);


            int cnt = 0;
            //gridview.Bands.Clear();
            string[] parts = "TEMEL BİLGİLER;GARNİ;DİĞER".Split(';');
            string[] starts = "idx;Garni1CM;BedenAraligi;".Split(';');
            for (int i = 0; i < parts.Length; i++)
            {
                GridBand gb = new DevExpress.XtraGrid.Views.BandedGrid.GridBand();
                gb.Caption = "<b>" + parts[i] + "</b>";
                //gb.ImageIndex = imageCnt++ % 7;
                gb.Name = "gb" + gb.ImageIndex.ToString();
                //TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gvMetraj.Bands.Add(gb);

                for (int i2 = cnt; i2 < gvMetraj.Columns.Count; i2++)
                {
                    //if (gvMetraj.Columns[cnt].FieldName == "CustomerId")
                    //    continue;

                    if (gvMetraj.Columns[cnt].FieldName == starts[i + 1] && cnt > 0)
                        break;

                    gvMetraj.Bands[i].Columns.Add(gvMetraj.Columns[cnt]);

                    //if (gvMetraj.Columns[cnt].FieldName == "BrandId")
                    //    gvMetraj.Bands[i].Columns.Add(gvMetraj.Columns["CustomerId"]);

                    cnt++;
                }
            }

            gvMetraj.OptionsView.AllowHtmlDrawHeaders = true;
            //gvMetraj.Columns["CustomerId"].VisibleIndex = gvMetraj.Columns["BrandId"].VisibleIndex + 1;
            //gvMetraj.Columns["CustomerId"].ColumnEdit = RI(Rp.V_Customer);
            //gvMetraj.Columns["CustomerId"].FilterMode = ColumnFilterMode.DisplayText;

            ds.BM.TableNewRow += new DataTableNewRowEventHandler(BM_TableNewRow);
            gvMetraj.ShowingEditor += new System.ComponentModel.CancelEventHandler(gvMetraj_ShowingEditor);
            //GridColumn colCustomer = gvMetraj.Columns.AddField("CustomerId");
            //colCustomer.ColumnEdit = RI(Rp.V_Customer);
            //colCustomer.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
            //colCustomer.VisibleIndex = gvMetraj.Columns["BrandId"].VisibleIndex + 1;
            //colCustomer.FilterMode = ColumnFilterMode.DisplayText;
            ////(colCustomer.ColumnEdit as RepositoryItemGridLookUpEdit).TextEditStyle = TextEditStyles.DisableTextEditor;
            //colCustomer.OptionsColumn.AllowEdit = false;
            //gvMetraj.CellMerge += new CellMergeEventHandler(gvMetraj_CellMerge);

            pivotGridControl1.DataSource = bsBM;


            InitPG();

            btnGetir.ItemClick += btnGetir_ItemClick;
            btnKaydet.ItemClick += btnKaydet_ItemClick;

            gleBrand.Edit.Assign(RI(Rp.Brand));
            //gleBrand.BorderStyle = BorderStyles.Default;

            xBrand.ItemClick += xBrand_ItemClick;
            xDosyaNo.ItemClick += xDosyaNo_ItemClick;

            splitContainerControl2.AutoSize();
        }

        void xDosyaNo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            teDosyaNo.EditValue = string.Empty;
        }

        void xBrand_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gleBrand.EditValue = null;
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //ds.BM.Columns["CustomerId"].Expression = 
            ds.BM.Columns["BirimMetraj"].Expression = null;

            Save();

            //ds.BM.Columns["CustomerId"].Expression = "Parent(FK_BM_Brand_BrandId).CustomerId";
            ds.BM.Columns["BirimMetraj"].Expression = "AVG(Child(FK_BMLines_BM_idx).BirimMetraj)";
        }

        void btnGetir_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            throw new NotImplementedException();
        }

        //TODO: Bu metod çağırılmıyor!
        void btnKaydet2_Click(object sender, EventArgs e)
        {
            gvLines.EndEditing();
            gvMetraj.EndEditing();
            gv1.EndEditing();
            if (gleBrand.EditValue == null && teDosyaNo.EditValue.ToString().Trim() == string.Empty)
            {
                XtraMessageBox.Show("Bir DosyaNo ve/veya Marka seçin.");
                return;
            }

            if (btnKaydet.Enabled)
                if (ds.HasChanges())
                    if (XtraMessageBox.Show("Değişiklikleri kaydetmek ister misiniz?", "Critical", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        btnKaydet.PerformClick();

            ds.Clear();
            ds.AcceptChanges();

            GetDetails("BM;BMLines", "GetBM", teDosyaNo.EditValue.ToStr(), intParse(gleBrand.EditValue));
            gvMetraj.BestFitColumns();
            //gvMetraj.MoveLast();
            //gvMetraj.TopRowIndex = gvMetraj.FocusedRowHandle;

            gvLines.BestFitColumns();

        }

        void gvMetraj_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gvLines.BestFitColumns();
        }

        void BM_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
        }

        void gvMetraj_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = false;   // intParse(gvMetraj.GetFocusedRowCellValue("UserId")) != WhoAmI;
        }

        //Skin currentSkin = CommonSkins.GetSkin(defaultLookAndFeel1.LookAndFeel);
        //Color c = currentSkin.TranslateColor(SystemColors.Control);

        //PivotGridField pgfCustomer;
        PivotGridField pgfBrand;

        void InitPG()
        {
            pivotGridControl1.DataSource = bsBM;
            pivotGridControl1.BeginUpdate();
            //AddNewField("Vendor", PivotArea.FilterArea);

            pgfBrand = AddNewField("BrandId", PivotArea.RowArea);
            //pgfCustomer = AddNewField("CustomerId", PivotArea.RowArea);

            //pgfCustomer = new PivotGridField("CustId", PivotArea.RowArea);
            //pgfCustomer.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
            //pgfCustomer.UnboundFieldName = "CustId";
            //pivotGridControl1.Fields.Add(pgfCustomer);

            PivotGridFieldBase[] pgf1 = new PivotGridFieldBase[1];
            //pgf1[0] = pgfCustomer;
            //pgfCustomer.FieldEdit = RI(Rp.V_Customer);
            //pgf1[0].ExpandedInFieldsGroup = false;

            pgf1[0] = pgfBrand;
            pgfBrand.FieldEdit = RI(Rp.Brand);
            pivotGridControl1.Groups.Add(pgf1, "CustomerBrand");

            AddNewField("Line", PivotArea.ColumnArea);
            AddNewField("BirimMetraj", PivotArea.DataArea).Width = 40;
            //AddNewField("MK", PivotArea.DataArea);

            //pivot.Fields["Gramaj"].Appearance.Cell.BackColor = CommonSkins.GetSkin(DevExpress.LookAndFeel.UserLookAndFeel.Default).TranslateColor(SystemColors.Control);
            //pivot.Fields["Gramaj"].Appearance.Cell.ForeColor = Color.Indigo;
            //pivot.Fields["Vendor"].Appearance.Cell.BorderColor = Color.BlueViolet;

            pivotGridControl1.OptionsBehavior.ApplyBestFitOnFieldDragging = true;
            pivotGridControl1.OptionsView.ShowRowGrandTotals = false;
            pivotGridControl1.OptionsView.ShowColumnGrandTotals = false;
            pivotGridControl1.EndUpdate();

            //pivotGridControl1.EditValueChanged += new DevExpress.XtraPivotGrid.EditValueChangedEventHandler(pivotGridControl_EditorValueChanged);
            pivotGridControl1.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pgc_FieldValueDisplayText);
            //pivotGridControl1.CustomDrawCell+=new PivotCustomDrawCellEventHandler(pivotGridControl1_CustomDrawCell);

            //pivotGridControl1.CustomUnboundFieldData+=new CustomFieldDataEventHandler(pivotGridControl1_CustomUnboundFieldData);
            //pivotGridControl1.FieldValueDisplayText+=new PivotFieldDisplayTextEventHandler(pivotGridControl1_FieldValueDisplayText);

            pivotGridControl1.CellClick += new PivotCellEventHandler(pivotGridControl1_CellClick);

            DrillDownGrid(gv1, bsBM);

        }

        void pivotGridControl1_CellClick(object sender, DevExpress.XtraPivotGrid.PivotCellEventArgs e)
        {
            gc1.DataSource = e.CreateDrillDownDataSource();
        }

        private void pivotGridControl1_CustomUnboundFieldData(object sender, DevExpress.XtraPivotGrid.CustomFieldDataEventArgs e)
        {
            //if (e.Field == pgfCustomer)
            //    e.Value = AppSession.Lookups.Brand.FindByBrandId(Convert.ToInt32(e.GetListSourceColumnValue("BrandId"))).CustomerId;
        }

        void pgc_FieldValueDisplayText(object sender, PivotFieldDisplayTextEventArgs e)
        {
            if (e.Value != null && e.Field != null && e.Field.FieldEdit != null)
                e.DisplayText = (e.Field.FieldEdit as RepositoryItemGridLookUpEdit).GetDisplayTextByKeyValue(e.Value).ToString();
        }

        private PivotGridField AddNewField(string FieldName, PivotArea pa)
        {
            PivotGridField fd = new PivotGridField();
            fd.FieldName = fd.Caption = FieldName;
            fd.SetAreaPosition(pa, 0);
            if (pa == PivotArea.DataArea)
            {
                fd.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Average;
                //if (fd.FieldName == "MK")
                //fd.FieldEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCalcEdit();
                fd.CellFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                fd.CellFormat.FormatString = "{0:#,###.##}";
            }
            pivotGridControl1.Fields.Add(fd);
            return fd;
        }

        void gvMetraj_CellMerge(object sender, CellMergeEventArgs e)
        {
            GridView view = sender as GridView;
            e.Merge = view.GetRowCellDisplayText(e.RowHandle1, e.Column) == view.GetRowCellDisplayText(e.RowHandle2, e.Column) &&
                view.GetRowCellDisplayText(e.RowHandle1, "DosyaNo") == view.GetRowCellDisplayText(e.RowHandle2, "DosyaNo");

            e.Handled = true;
        }


        //DateTime LastModified = new DateTime(2000, 1, 1);
        //void btnGuncelle_Click(object sender, EventArgs e)
        //{
        //    GetDetails("xTarih;BM;BMLines", "GetBM", LastModified);
        //    LastModified = ds.xTarih[0].Tarih;
        //    gvMetraj.BestFitColumns();
        //    //gvMetraj.MoveLast();
        //    //gvMetraj.TopRowIndex = gvMetraj.FocusedRowHandle;
        //}

        void bsBM_CurrentChanged(object sender, EventArgs e)
        {
            if (bsBM.Current != null)
                txtInfo.Caption = ((DataRowView)bsBM.Current).Row["Model"].ToString() + " | " +
                    ((DataRowView)bsBM.Current).Row["Kalip"].ToString();
        }

        void gvMetraj_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
                switch (e.Column.FieldName)
                {
                    case "BrandId":
                    case "BirimMetraj":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;
                }
        }
    }
}